package cn.bbstone.pisces2.ui.handlers;

import javax.inject.Inject;
import javax.inject.Named;

import org.eclipse.e4.core.di.annotations.CanExecute;
import org.eclipse.e4.core.di.annotations.Execute;
import org.eclipse.e4.core.di.annotations.Optional;
import org.eclipse.e4.core.services.events.IEventBroker;
import org.eclipse.e4.ui.di.UIEventTopic;
import org.eclipse.e4.ui.services.IServiceConstants;
import org.eclipse.e4.ui.workbench.IWorkbench;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Shell;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.bbstone.pisces2.client.ClientStarter;
import cn.bbstone.pisces2.client.base.ClientCache;
import cn.bbstone.pisces2.cmm.Pi2ContextUtil;
import cn.bbstone.pisces2.cmm.UIConst;
import cn.bbstone.pisces2.listener.OpEnum;
import cn.bbstone.pisces2.server.ServerStarter;
import cn.bbstone.pisces2.ui.base.enums.CmdEnum;
import cn.bbstone.pisces2.ui.base.notify.Pi2Events;

public class ShutdownHandler {
	private static Logger log = LoggerFactory.getLogger(ShutdownHandler.class);

	@Inject
	IEventBroker eventBroker;

//	@Inject
//	private JobService jobService;
//	@Inject
//	private LogsService logsService;

	
	private boolean canExecuted = false;


	private void disabledButton() {
		this.canExecuted = false;
	}
	
	private void enabledButton() {
		this.canExecuted = true;
	}
	
	
	@CanExecute
	public boolean canExecute() {
//		log.info("stop-canExecuted: {}", this.canExecuted);
		return this.canExecuted;
	}

	@Execute
	public void execute(IWorkbench workbench, @Named(IServiceConstants.ACTIVE_SHELL) Shell shell) {
//		System.out.println((this.getClass().getSimpleName() + " called"));
		log.info((this.getClass().getSimpleName() + " called")); //$NON-NLS-1$

		String runAs = Pi2ContextUtil.getRunAs();
		if (runAs == null || runAs.length() == 0) {
			log.error("cannot shutdown, unkonwn error."); //$NON-NLS-1$
		}
		// runAs server
		if (UIConst.RUN_AS_SERVER.equals(Pi2ContextUtil.getRunAs())) {
			if (Pi2ContextUtil.isRunning()) {
				// shutdown with user confirmation
				if (Pi2ContextUtil.isClientConnected()) {
					if (MessageDialog.openConfirm(shell, Messages.dialog_title_confirm, //$NON-NLS-1$
							Messages.dialog_content_shutdown_with_client_conn)) {
						doShutdownServer();
					}
				} else {
					if (MessageDialog.openConfirm(shell, Messages.dialog_title_confirm, //$NON-NLS-1$
							Messages.dialog_content_shutdown_server)) {
						doShutdownServer();
					}
				}
			} else {
				boolean ok = MessageDialog.openConfirm(shell, Messages.dialog_title_confirm, Messages.dialog_content_shutdown_server_notstart); //$NON-NLS-1$
				if (ok) {
					notifyClearServerUIData();
				}
			}
		}
		// runAs client
		if (UIConst.RUN_AS_CLIENT.equals(Pi2ContextUtil.getRunAs())) {
			if (Pi2ContextUtil.isRunning()) {
				if (MessageDialog.openConfirm(shell, Messages.dialog_title_confirm, //$NON-NLS-1$
						Messages.dialog_content_shutdown_client)) {
					doShutdownClient();
				}
			} else {
				boolean ok = MessageDialog.openConfirm(shell, Messages.dialog_title_confirm, Messages.dialog_content_shutdown_client_notstart); //$NON-NLS-1$
				if (ok) {
					notifyClearClientUIData();
				}
			}
		}
	}

	public void doShutdownServer() {
		ServerStarter.shutdown();
		Pi2ContextUtil.setRunning(false);
		
		notifyClearServerUIData();
		eventBroker.post(Pi2Events.OPERATION, OpEnum.s101_server_shutdown.getDisplayText());
		
		Pi2ContextUtil.reset();
		
		// do cancel jobs/dispose when exit
//		jobService.cancelJobs();
//		logsService.dispose();
	}
	
	public void doShutdownClient() {
		ClientStarter.shutdown();
		Pi2ContextUtil.setRunning(false);
		ClientCache.cleanAll();
		
		notifyClearClientUIData();
		eventBroker.post(Pi2Events.OPERATION, OpEnum.s101_client_shutdown.getDisplayText());
		
		Pi2ContextUtil.reset();
		// do cancel jobs/dispose when exit
//		jobService.cancelJobs();
//		logsService.dispose();
	}
	
	private void notifyClearServerUIData() {
		eventBroker.post(Pi2Events.SERVER_SHUTDOWN_SAVEPOINT, null);
		eventBroker.post(Pi2Events.SERVER_SHUTDOWN_CONNINFO, null);
		eventBroker.post(Pi2Events.SERVER_SHUTDOWN_FILELIST, null);
		
		this.disabledButton();
		eventBroker.post(Pi2Events.SHUTDOWN, CmdEnum.stop);
	}
	private void notifyClearClientUIData() {
		eventBroker.post(Pi2Events.CLIENT_SHUTDOWN_SAVEPOINT, null);
		eventBroker.post(Pi2Events.CLIENT_SHUTDOWN_CONNINFO, null);
		eventBroker.post(Pi2Events.CLIENT_SHUTDOWN_FILELIST, null);
		this.disabledButton();
		eventBroker.post(Pi2Events.SHUTDOWN, CmdEnum.stop);
		
	}
	
	// on server/client start, disabled stop button
	@Inject
	@Optional
	void onStart(final @UIEventTopic(Pi2Events.STARTUP) CmdEnum cmdEnum) {
//		log.info("@ShutdownHandler handling onStart");
		// when start pi2(server/client), stop button enabled
		if (CmdEnum.startup.equals(cmdEnum)) {
			this.enabledButton();
		}

	}
	

}
